import baseConfig from '@/config/base-config'

const prefix = baseConfig.LOCAL_STORAGE_PREFIX

const getStoreKey = (key: string): string => `${prefix}${key}`
export const localStore = {
  /**
   * 存储
   * @param key 键
   * @param value 值
   * @param expire 过期时间（时间戳）
   */
  set(key: string, value: any, expire?: number) {
    const storeKey = getStoreKey(key)
    const cache: any = {
      value,
      expire
    }
    if (expire) {
      cache.expire = new Date().getTime() + expire
    }
    localStorage.setItem(storeKey, JSON.stringify(cache))
  },
  //取出数据
  get<T>(key: string, defaultValue: any = null): T {
    const storeKey = getStoreKey(key)
    const cacheStore = localStorage.getItem(storeKey)
    if (cacheStore) {
      const cache = JSON.parse(cacheStore)
      const expire = cache?.expire
      if (expire && expire < new Date().getTime()) {
        localStorage.removeItem(storeKey)
        return defaultValue
      }
      return cache.value
    }
    return defaultValue
  },
  // 删除数据
  remove(key: string) {
    localStorage.removeItem(getStoreKey(key))
  },
  //清除数据
  clear() {
    localStorage.clear()
  }
}
